/**
 * 
 */
package com.thor.palmmall.dao.elecharges;

import java.util.ArrayList;
import java.util.List;

import com.thor.commons.query.QueryCondition;
import com.thor.commons.query.QueryOrder;
import com.thor.commons.query.SQLSubquery;
import com.thor.commons.query2.QueryConditionDecoder2;
import com.thor.commons.query2.QueryOrderDecoder2;
import com.thor.palmmall.api.elecharges.EleChargesBillService;
import com.thor.palmmall.api.elecharges.EleChargesBillState;
import com.thor.palmmall.dao.common.QueryDecoderSupport;

/**
 * @author NuoSa
 *
 * @since 1.0
 */
public class EleChargesBillQueryDecoder extends QueryDecoderSupport
    implements QueryConditionDecoder2, QueryOrderDecoder2 {

  private static EleChargesBillQueryDecoder instance = null;

  public static synchronized EleChargesBillQueryDecoder getInstance() {
    if (instance == null) {
      instance = new EleChargesBillQueryDecoder();
    }
    return instance;
  }

  private EleChargesBillQueryDecoder() {

  }

  @Override
  public void decodeOrder(QueryOrder order, SQLSubquery sql) {
    super.decodeOrder(order, sql);
    if (EleChargesBillService.ORDER_BY_BILL_NUMBER.equals(order.getField())) {
      sql.appendOrder("o.billNumber", order.getDirection());

    } else if (EleChargesBillService.ORDER_BY_STATE.equals(order.getField())) {
      sql.appendOrder("o.state", order.getDirection());

    } else if (EleChargesBillService.ORDER_BY_CREATE_TIME.equals(order.getField())) {
      sql.appendOrder("o.createInfo.time", order.getDirection());
    }
  }

  @Override
  public void decodeCondition(QueryCondition condition, SQLSubquery sql) {
    super.decodeCondition(condition, sql);

    final String operation = condition.getOperation();
    final Object parameter = condition.getParameter();
    if (EleChargesBillService.CONDITION_BILL_NUMBER_EQUALS.equals(operation)) {
      sql.appendConditionEx("o.billNumber = :billNumber", parameter);

    } else if (EleChargesBillService.CONDITION_BILL_NUMBER_LIKE.equals(operation)) {
      sql.appendConditionEx("o.billNumber like :billNumber", "%" + parameter + "%");

    } else if (EleChargesBillService.CONDITION_STATE_IN.equals(operation)) {
      List<EleChargesBillState> states = new ArrayList<EleChargesBillState>();
      for (Object obj : condition.getParameters()) {
        if (obj instanceof EleChargesBillState) {
          states.add((EleChargesBillState) obj);
        } else if (obj instanceof String) {
          states.add(EleChargesBillState.valueOf((String) obj));
        }
      }
      sql.appendCondition("o.state in (:states)", "states", states);
    } else if (EleChargesBillService.CONDITION_USERNUBER_EQUALS.equals(operation)) {
      sql.appendConditionEx("o.userNumber = :userNumber", parameter);
    } else if (EleChargesBillService.CONDITION_NOTIFYFLAG_EQUALS.equals(operation)) {
      sql.appendConditionEx("o.notifyFlag = :notifyFlag", parameter);
    }
  }

}
